using System.Runtime.InteropServices;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class BeeChaseState : BaseState {
    
    private Attack attack;
    private bool isAttack;
    private Vector3 target;
    private Vector3 moveDir;
    private float attackRateCounter;    // 攻击事件间隔计时器

    public override void OnEnter(Enemy enemy) {
        currentEnemy = enemy;
        Debug.Log("Bee Chase");
        currentEnemy.currentSpeed = currentEnemy.chaseSpeed;
        currentEnemy.ani.SetBool("isChase", true);
        attack = enemy.GetComponent<Attack>();
    }

    public override void LogicUpdate() {
        // 如果丢失目标超过一定时间则重新回到巡逻状态
        if (currentEnemy.lostTimeCounter <= 0) {
            currentEnemy.SwitchState(NPCState.Patrol);
        }

        // 发现玩家，则冲向玩家，因为player的position是脚底位置，并且蜜蜂攻击的时候会有一点小的转向位移，所以y值+1.5
        target = new Vector3(currentEnemy.attacker.position.x, currentEnemy.attacker.position.y + 1.5f, 0);

        // 攻击时间间隔计时器
        attackRateCounter -= Time.deltaTime;

        // 移动到目标位置之后，对玩家发起攻击
        if (Mathf.Abs(target.x - currentEnemy.transform.position.x) <= attack.attackRange && Mathf.Abs(target.y - currentEnemy.transform.position.y) <= attack.attackRange) {
            // 攻击
            isAttack = true;
            if (!currentEnemy.isHurt) {     // 如果不加这个判断，在蜜蜂发起攻击时则无法被击退
                currentEnemy.rb.velocity = Vector2.zero;  // 到达玩家位置，此时位移应该为0
            }

            // 每当攻击时间间隔结束则攻击一次
            if (attackRateCounter <= 0) {
                currentEnemy.ani.SetTrigger("attack");
                attackRateCounter = attack.attackRate;
            }
        } else {
            isAttack = false;
        }

        // 获得移动方向
        moveDir = (target - currentEnemy.transform.position).normalized;

        // 翻转Bee朝向
        if (moveDir.x > 0) {
            currentEnemy.transform.localScale = new Vector3(-1, 1, 1);
        }
        if (moveDir.x < 0) {
            currentEnemy.transform.localScale = new Vector3(1, 1, 1);
        }
    }

    public override void PhysicsUpdate() {
        if (!currentEnemy.isWait && !currentEnemy.isHurt && !currentEnemy.isDead && !isAttack) {
            // 朝着指定方向以指定的速度进行移动
            currentEnemy.rb.velocity = moveDir * currentEnemy.currentSpeed * Time.deltaTime;
        }
    }

    public override void OnExit() {
        currentEnemy.ani.SetBool("isChase", false);
        Debug.Log("Bee Chase Exit");
    }

}
